<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;
use App\Models\Role;
use Hash;
use Validator;

class AdminUsersController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //搜索
        //构建查询器
        $query = Admin::where('id','>',0);
        // 获取搜索关键词
        $username = $request->get('username');
        // 开始时间
        $datemin = $request->get('datemin');
        // 结束时间
        $datemax = $request->get('datemax');
        if(!empty($datemin) || !empty($datemax)){
            $datemin = date('Y-m-d H:i:s', strtotime($datemin.' 00:00:00'));
            $datemax = date('Y-m-d H:i:s', strtotime($datemax.' 23:59:59'));
            $query->whereBetween('created_at',[$datemin,$datemax]);
        }

        if(!empty($username)){
            $query->where('username', 'like', "%{$username}%");
        }
        // 分页 withTrashed显示所有数据，包括软删除的数据
        $data = $query->orderBy('created_at','desc')->orderBy('deleted_at')->withTrashed()->paginate($this->pagesize);
        return view('admin.admin-users.index',compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.admin-users.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'username' => 'required|unique:admins,username',
            'truename' => 'required',
            'password' => 'required|confirmed',
            'phone' => 'nullable|phone'
        ]);
        $post = $request->except('_token','password_confirmation');
        $pwd = $post['password'];
        $post['password'] = bcrypt($pwd);
        $adminUserModel = Admin::create($post); //返回一个用户模型
        //此处可以添加发邮件，现省略
        return redirect(route('admin.admin-users.index'))->with('success','添加用户成功');
    }

    /**
     * 用户展示
     */
    public function show($id)
    {
        //软删除用户也可显示
        // $model = Admin::find($id);
        $model = Admin::withTrashed()->find($id);
        return view('admin.admin-users.show',compact('model'));
    }

    /**
     * 修改显示
     */
    public function edit(int $id)
    {
        $model = Admin::find($id);
        return view('admin.admin-users.edit',compact('model'));
    }

    /**
     * 修改处理
     */
    public function update(Request $request, int $id)
    {
        // dd($request->except('_token'));
        $model = Admin::find($id);
        $spass = $request->get('spassword'); //原密码 明文
        $oldpass = $model->password;    //原密码 加密
        //检查明文密码和密文是否一致
        $bool = Hash::check($spass, $oldpass);

        if($bool){
            //修改
            $data = $request->only([
                'truename',
                'password',
                'phone',
                'sex',
                'status',
                'email'
            ]);
            //是否修改密码
            if(!empty($data['password'])){
                $data['password'] = bcrypt($data['password']);
            }else{
                unset($data['password']);
            }
            $model->update($data);
            return redirect(route('admin.admin-users.index'))->with('success','修改用户成功');
        }
        return redirect(route('admin.admin-users.edit',$model))->withErrors(['error'=>'原密码不正确']);
    }

    /**
     * 删除
     */
    public function destroy($id)
    {
        Admin::find($id)->delete();
        return ['status'=>0, 'msg'=>'删除成功！'];
    }

    /**
     * 全选删除
     */
    public function delall(Request $request) {
        $ids = $request->get('id');
        Admin::destroy($ids);
        return ['status'=>0, 'msg'=>'批量删除成功！'];
    }

    /**
     * 还原(软删除)
     */
    public function restore($id)
    {
        Admin::onlyTrashed()->where('id',$id)->restore();   // 软删除还原
        return redirect(route('admin.admin-users.index'))->with('success', '还原成功');
    }

    /**
     * 用户--启用
     */
    public function start(Request $request) {
        $id = $request->get('id');
        $model = Admin::find($id);
        //修改
        $model->update(['status'=>1]);
        return ['status'=>0, 'msg' => '已启用'];
    }

    /**
     * 用户--禁用
     */
    public function stop(Request $request) {
        $id = $request->get('id');
        $model = Admin::find($id);
        //修改
        $model->update(['status'=>0]);
        return ['status'=>0, 'msg'=>'已禁用'];
    }

    /**
     * 分配权限
     */
    public function role(Request $request, Admin $admin){
        //判断是否是post提交
        if($request->isMethod('post')){
            //ajax 必须使用手动创建器，这样可控制返回状态，否则验证不满足条件时，laravel默认返回422状态
            $validator = Validator::make($request->all(),[
                'role_id' => 'required'
            ],['role_id.required'=>'必须选择角色']);
            if($validator->fails()) {
                $msg = $validator->errors()->first();
                return [
                    'status' => '-1',
                    'msg' => $msg
                ];
            }
            $data = [
                'role_id'=>$request->role_id,
            ];
            $admin->update($data);
            return ['status'=>0,'msg'=>'分配角色成功'];
        }

        //读取所有角色
        $roleAll = Role::all();
        return view('admin.admin-users.role',compact('roleAll','admin'));
    }

}
